package com.tourManagement.service.impl;

import cn.hutool.crypto.digest.MD5;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanListHandler;
import com.tourManagement.entity.行程信息;
import com.tourManagement.service.行程管理Service;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author xiaoRan
 */
@Service
public class 行程管理ServiceImpl implements 行程管理Service {
    private final String TABLE_NAME = "travel_info";
//    private final String ID = "id";
//    private final String ROUTE_ID = "route_id";

    @Override
    public int insert(行程信息 data) throws SQLException {
        String tid = genTid(data);
        data.setId(tid);
        data.setCreateTime(new Date());
        return Db.use().insert(Entity.create(TABLE_NAME).parseBean(data, true, false));
    }

    @Override
    public int delete(String id) throws SQLException {
        return Db.use().del(Entity.create(TABLE_NAME).set("id", id));
    }

    @Override
    public int update(行程信息 data) throws SQLException {
        data.setRouteId(null);
        data.setDay(null);
        data.setEndTime(null);
        return Db.use().update(Entity.create(TABLE_NAME).parseBean(data, true, true), Entity.create(TABLE_NAME).set("id", data.getId()));
    }

    @Override
    public List<行程信息> selectList(Integer routeId) throws SQLException {
        String sql = "select * from travel_info where route_id=? order by day asc, end_time";
        return Db.use().query(sql, new BeanListHandler<>(行程信息.class), routeId);
    }

    @Override
    public List<行程信息> selectList(Integer routeId, Integer day) throws SQLException {
        String sql = "select * from travel_info where route_id=? and day=? order by end_time";
        return Db.use().query(sql, new BeanListHandler<>(行程信息.class), routeId, day);
    }

    /**
     * 生成行程id
     *
     * @param data 行程信息
     * @return 16位行程id
     */
    private String genTid(行程信息 data) {
        Integer routeId = data.getRouteId();
        Integer day = data.getDay();
        Date endTime = data.getEndTime();
        String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(endTime);
        StringBuilder s = new StringBuilder();
        String str = s.append(routeId).append("/").append(day).append(dateStr).toString();
        return MD5.create().digestHex16(str);
    }
}
